package com.thon.controller.rest;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.thon.commons.utils.OrderNoGenerator;
import com.thon.controller.rest.dto.CouponDto;
import com.thon.controller.util.BaseController;
import com.thon.dao.util.Page;
import com.thon.entity.project.Project;
import com.thon.entity.project.ProjectSupport;
import com.thon.entity.user.Coupon;
import com.thon.entity.user.FundDetail;
import com.thon.entity.user.SendTo;
import com.thon.entity.user.User;
import com.thon.service.message.TextMessageService;
import com.thon.service.project.ProjectService;
import com.thon.service.project.ProjectSupportService;
import com.thon.service.user.CouponService;
import com.thon.service.user.FundDetailService;
import com.thon.service.user.SendToService;
import com.thon.service.user.UserService;

/**
 * @file ProjectIncomeController.java
 * @author wang
 * @data 2014-6-17
 * @description: TODO
 */
@Controller
@RequestMapping(value = "/api/project/income")
@SuppressWarnings({ "rawtypes", "unchecked" })
public class ProjectIncomeRestController extends BaseController{
	
	@Autowired 
	private CouponService couponService;
	@Autowired
	private UserService userService;
	@Autowired
	private SendToService sendToService;
	@Autowired
	private FundDetailService fundDetailService;
	@Autowired
	private TextMessageService textMessageService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private ProjectSupportService projectSupportService;

	
	//获取优惠券详情
	@RequestMapping(value = "/coupon/detail", method = RequestMethod.GET)
	public ResponseEntity<?>  provideCoupon(@RequestParam(value = "uid")int uid,
											@RequestParam(value = "no")String no) {
		Coupon c = couponService.getCoupon(uid, no);
		Project project = projectService.getProject(c.getProject().getId());
		Long supportCount = projectSupportService.countProjectSupport(c.getProject().getId());
		int newsupportCount = supportCount.intValue();
		project.setSupportCount(newsupportCount);
		c.setProject(project);
		couponService.update(c);
		return new ResponseEntity(c,HttpStatus.OK);
	}
	//列出所有优惠券列表
	@RequestMapping(value = "/coupon/listall", method = RequestMethod.GET)
	public ResponseEntity<?> listAllCoupons( @RequestParam(required=false,value="projectId") int ProjectId,
										     @RequestParam(value="p",defaultValue="1") int pageNo,
			   								 @RequestParam(value="s",defaultValue="10") int pageSize){
		
		Page<Coupon> page = new Page<Coupon>();
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		page.setTotalCount(page.getTotalCount());
		if(ProjectId==0){
			page = couponService.findAllCoupons(page);
			return new ResponseEntity(page,HttpStatus.OK);
		}
		page = couponService.findCouponByProjectId(page, ProjectId);
		return new ResponseEntity(page,HttpStatus.OK);
		
	}
	//获取user未使用优惠券列表
	@RequestMapping(value="/list/unusedcoupons",method=RequestMethod.GET)
	public ResponseEntity<?> listunusedcoupons(@RequestParam(value="uid") int uid,
											   @RequestParam(value="p",defaultValue="1") int pageNo,
											   @RequestParam(value="s",defaultValue="4") int pageSize){
		Page<Coupon> page = new Page<Coupon>();
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		page.asc("overdueDate");
		page = couponService.listCoupon(page, uid);
		Page<CouponDto> pageDto = new Page<CouponDto>();
		List<CouponDto> list = Lists.newArrayList();
		for(Coupon coupon:page.getResult()){
			//FIXME	Dozer配置文件映射
			CouponDto couponDto = CouponDto.covert(new CouponDto(), coupon);
			list.add(couponDto);
		}
		pageDto.setResult(list);
		pageDto.setPageNo(page.getPageNo());
		pageDto.setPageSize(page.getPageSize());
		pageDto.setTotalCount(page.getTotalCount());
		return new ResponseEntity(pageDto, HttpStatus.OK);
	}
	//获取user废弃优惠券列表
	@RequestMapping(value="/list/usedcoupons",method=RequestMethod.GET)
	public ResponseEntity<?> listunusercoupons(@RequestParam(value="uid") int uid,
											   @RequestParam(value="p",defaultValue="1") int pageNo,
											   @RequestParam(value="s",defaultValue="4") int pageSize){
		Page<Coupon> page = new Page<Coupon>();
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		page = couponService.listUsedCoupon(page, uid);
		Page<CouponDto> pageDto = new Page<CouponDto>();
		List<CouponDto> list = Lists.newArrayList();
		for(Coupon coupon:page.getResult()){
			CouponDto couponDto = CouponDto.covert(new CouponDto(), coupon);
			list.add(couponDto);
		}
		pageDto.setResult(list);
		pageDto.setPageNo(page.getPageNo());
		pageDto.setPageSize(page.getPageSize());
		pageDto.setTotalCount(page.getTotalCount());
		return new ResponseEntity(pageDto, HttpStatus.OK);
		
	}
	
	//领取优惠券
	@RequestMapping(value = "/coupon/get",method = {RequestMethod.POST, RequestMethod.GET})
	public ResponseEntity<?> getCoupon(@RequestParam(value = "uid") int uid,
									   @RequestParam(value = "id") int id,
									   @RequestParam(required=false,value = "addressId") Integer addressId,
									   HttpServletRequest request) throws IOException {
		User user = userService.getUser(uid);
		Coupon oldCoupon = couponService.getCouponById(id);		
		if ( oldCoupon.getLabel().equals(Coupon.TYPE_GOODS)) {
			oldCoupon.setCouponStatus(Coupon.STATUS_USED);
			oldCoupon.setAddressId(addressId);
			couponService.update(oldCoupon);
			//发送实物券编号给用户
			String phone = sendToService.getById(addressId).getPhone();
			String couponNo = oldCoupon.getCouponNo();
			String value = "#code#="+couponNo;
			textMessageService.tplSendSms(value, phone, TextMessageService.SEND_VERIFICATION_CODE);
			return new ResponseEntity(true, HttpStatus.OK);
			}

		else if (oldCoupon.getLabel().equals(Coupon.TYPE_MONEY)) {
			user.setFund(user.getFund() + oldCoupon.getCouponValue());
			userService.updateUser(user); 
			oldCoupon.setCouponStatus(Coupon.STATUS_DISCARD);
			couponService.update(oldCoupon);
			//现金券使用后，更新雅米宝明细
			FundDetail fundDetail = new FundDetail();
			fundDetail.setUser(user);
			fundDetail.setActionType(2);
			fundDetail.setAmount(oldCoupon.getCouponValue());
			fundDetail.setProject(oldCoupon.getProject());
			fundDetail.setTradeNo(OrderNoGenerator.generator("NO"));
			fundDetailService.saveFundDetail(fundDetail);
			return new ResponseEntity(true, HttpStatus.OK);
		}
		else if ( oldCoupon.getLabel().equals(Coupon.TYPE_ACTIVITY)) {
			HttpSession session = request.getSession();
			oldCoupon.setCouponStatus(Coupon.STATUS_USED);
			couponService.update(oldCoupon);
			//发送优惠券编号到用户手机
			String couponNo = oldCoupon.getCouponNo();
			String phone = user.getLoginName();
			String text = couponNo;
			String value = "#code#="+text;
			session.setAttribute(phone, text);
			textMessageService.tplSendSms(value, phone, TextMessageService.SEND_VERIFICATION_CODE);//触发短信的发送
			return new ResponseEntity(true, HttpStatus.OK);
		}
		else {
			return new ResponseEntity(false, HttpStatus.OK);
		}

	}
	
	//用户筛选优惠券
	@RequestMapping(value = "/coupon/{by}/{value}/list",method = RequestMethod.GET)
	public ResponseEntity<?> sortCouponByStatus(@RequestParam(value = "uid")int id,
												@PathVariable("by")String by,
												@PathVariable("value")String value,
												@RequestParam(value = "s",defaultValue = "10")int pageSize,
												@RequestParam(value = "p",defaultValue = "1")int pageNo) {
		//根据状态筛选
		if(by.equals("status")) {
			Page<Coupon> page = couponService.findCouponByStatus(value, id, pageNo, pageSize); 
			return new ResponseEntity(page, HttpStatus.OK);
		} 
		//根据类型筛选
		else if(by.equals("type")) {
			Page<Coupon> page = couponService.findCouponByType(value, id, pageNo, pageSize);
			return new ResponseEntity(page, HttpStatus.OK);
		}
		//根据作废时间筛选,时间戳
		else if(by.equals("overdueDt")) {
			Page<Coupon> page = couponService.findCouponByTime(value, id, pageNo, pageSize);
			return new ResponseEntity(page, HttpStatus.OK);
		}
		//根据发放时间筛选，传时间戳
		else if(by.equals("createDt")) {
			Page<Coupon> page = couponService.findCouponByCreateDt(value, id, pageNo, pageSize);
			return new ResponseEntity(page, HttpStatus.OK);
		}
		return new ResponseEntity(false, HttpStatus.OK);
	}
	
	//后台筛选优惠券
	@RequestMapping(value = "/admin/coupon/{by}/{value}/list",method = RequestMethod.GET)
	public ResponseEntity<?> sortCouponByValue(@PathVariable("by")String by,
											   @PathVariable("value")String value,
											   @RequestParam(value = "s",defaultValue = "10")int pageSize,
											   @RequestParam(value = "p",defaultValue = "1")int pageNo) {
			//根据状态筛选
			if(by.equals("status")){
				Page<Coupon> page = new Page<Coupon>();
				page.setPageNo(pageNo);
				page.setPageSize(pageSize);
				page.setTotalCount(page.getTotalCount());
				page = couponService.findCouponByStatus(page, value);
				return new ResponseEntity(page, HttpStatus.OK);
			}else if (by.equals("type")) {
				Page<Coupon> page = new Page<Coupon>();
				page.setPageNo(pageNo);
				page.setPageSize(pageSize);
				page.setTotalCount(page.getTotalCount());
				page = couponService.findCouponByType(page, value);
				return new ResponseEntity(page, HttpStatus.OK);
			}else {
				return new ResponseEntity(false, HttpStatus.OK);
			}
			
		}
	//根据优惠券（状态或者性质）和项目来筛选优惠券
	@RequestMapping(value="/admin/coupon/{by}/{value}/projectId",method = RequestMethod.GET)
	public ResponseEntity<?> listCouponByProject(@PathVariable(value="by") String by,
												 @PathVariable(value="value") String value,
												 @RequestParam(value="projectId") int ProjectId,
												 @RequestParam(value = "s",defaultValue = "10")int pageSize,
												 @RequestParam(value = "p",defaultValue = "1")int pageNo){
		Page<Coupon> page = new Page<Coupon>();
		page.setPageNo(pageNo);
		page.setPageSize(pageSize);
		page.setTotalCount(page.getTotalCount());
		if(ProjectId==0){
			page = couponService.findCouponByValue(page, by,  value);
			return new ResponseEntity(page, HttpStatus.OK);
		}
		page = couponService.findCouponPageByProject(page, by, value, ProjectId);
		return new ResponseEntity(page, HttpStatus.OK);
	}
	
	//列出所有项目的项目名
	@RequestMapping(value = "/projectName/list", method = RequestMethod.GET)
	public ResponseEntity<?> listALLProjectName(){
		List<Project> list = projectService.listAllProjectName();
		return new ResponseEntity(list, HttpStatus.OK);
	}
	
	//删除优惠券
	@RequestMapping(value = "/coupon/del", method = RequestMethod.GET)
	public ResponseEntity<?> delCoupon(@RequestParam(value = "cid") int cid) {
		
		Coupon oldCoupon = couponService.getCouponById(cid);
		couponService.del(oldCoupon);
		return new ResponseEntity(true,HttpStatus.OK);
	}
	
	//优惠券商品发送
	@RequestMapping(value = "/coupon/goods/send", method = RequestMethod.GET)
	public ResponseEntity<?> sendGoodsFromCoupon(@Valid SendTo sendto,
												 @RequestParam(value = "cid",required = true)int cid) {
		Coupon oldCoupon = couponService.getCouponById(cid);
		oldCoupon.setCouponStatus("3");
		String memo = oldCoupon.getMemo();
		oldCoupon.setMemo(memo);
		return new ResponseEntity(true, HttpStatus.OK);
	}
	
	
	//优惠券发放
	@RequestMapping(value="/coupon/selectUsers",method = RequestMethod.POST)
	public ResponseEntity<?> selectUsers(@RequestParam(value = "registDateStart",required = true)String registDateStart,
			@RequestParam(value = "comsumptionDateStart",required = true)String comsumptionDateStart,
			@RequestParam(value = "registDateEnd",required = true)String registDateEnd,
			@RequestParam(value = "comsumptionDateEnd",required = true)String comsumptionDateEnd,
			@RequestParam(value = "comsumptionFee",defaultValue = "0")int comsumptionFee,
			@RequestParam(value = "comsumptionTotleFee",defaultValue = "0")int comsumptionTotleFee,
			@RequestParam(value = "projectIds",defaultValue = "0")String projectIds,
			@RequestParam(value = "projectCategoryIds",defaultValue = "0")String projectCategoryIds,Model model) throws ParseException{
								
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");	
					Map<Integer,List<String>> user;
				
					user = projectSupportService.listProjectSupportsByProjectId(projectIds,(Date)sdf.parse(registDateStart), (Date)sdf.parse(comsumptionDateStart),(Date)sdf.parse(registDateEnd), (Date)sdf.parse(comsumptionDateEnd),comsumptionFee,comsumptionTotleFee,projectCategoryIds);
				    
					
					model.addAttribute("UserName", user.get(2));
					model.addAttribute("projectIds", user.get(3));
					model.addAttribute("UserIds",  user.get(1));
					
				   return new ResponseEntity(model, HttpStatus.OK);	
		
	}
	//优惠券发放
		@RequestMapping(value="/coupon/give",method = RequestMethod.POST)
		public ResponseEntity<?> giveCoupons(@Valid Coupon coupon,
				@RequestParam(value = "users",required = true)String users) throws ParseException{									
						String [] userID = users.split(",");
						if(userID==null||userID.length==0)
							 return new ResponseEntity(0, HttpStatus.OK);	
						
						Map<Integer,Integer> map = new HashMap<Integer,Integer>();
						for(int i=0;i<userID.length;i++)
						{
							String[] userProject = userID[i].split("=");
							if(userProject!=null&&userProject.length!=0)
							{
								map.put(Integer.parseInt(userProject[0]), Integer.parseInt(userProject[1]));
							}
						}
			
						if(map==null||map.size()!=0){
							Iterator<Integer> iter = map.keySet().iterator();
							Integer key,i;
							i=0;
							while(iter.hasNext())
							{
							    key = iter.next();
							    Coupon newcoupon = new Coupon();
								newcoupon.setCouponNo(OrderNoGenerator.randomnum(i++));
								newcoupon.setCouponStatus("0");
								newcoupon.setLabel(coupon.getLabel());
								newcoupon.setCouponExplain(coupon.getCouponExplain());
								newcoupon.setCouponValue(coupon.getCouponValue());
								newcoupon.setProject(projectService.getProject(map.get(key)));
								newcoupon.setUser(userService.getUser(key));
								newcoupon.setMemo(coupon.getMemo());
								newcoupon.setCreated_by(coupon.getCreated_by());
								newcoupon.setOverdueDate(coupon.getOverdueDate()); 
								couponService.save(newcoupon);
							}
						}					
						
					   return new ResponseEntity(map.size(), HttpStatus.OK);	
			
		}
	//实物券、虚拟券后台管理使用接口
	@RequestMapping(value="/admin/coupon/use",method = RequestMethod.POST)
	public ResponseEntity<?> updateCouponStatus(@RequestParam(value="no")  String no,
												@RequestParam(value="memo")  String memo){
		Coupon coupon = couponService.getCouponByNo(no);
		if(coupon==null)
			return new ResponseEntity(false, HttpStatus.OK);
		coupon.setCouponStatus("2");
		coupon.setMemo(memo);
		couponService.update(coupon);
			return new ResponseEntity(true, HttpStatus.OK);
	}
	//验证优惠券编号是否存在
	@RequestMapping(value="/check/coupon/no")
	@ResponseBody
	public ResponseEntity<?> check_coupon_no(@RequestParam(value="no") String no){
		
		Coupon coupon = couponService.getCouponByNo(no);
		
			return new ResponseEntity(coupon, HttpStatus.OK);

		
	}

}
